<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Common;

use Hyperf\Utils\Contracts\Arrayable;
use Hyperf\Utils\Contracts\Jsonable;
use Psr\Http\Message\ResponseInterface;

trait ApiResponse
{
    /**
     * @param array|Arrayable|Jsonable $data 数据
     * @return ResponseInterface 返回ResponseInterface
     */
    protected function success($data): ResponseInterface
    {
        return $this->response->json($this->data($data));
    }

    /**
     * @param string $message 消息
     * @param int $code 消息码
     * @param array|Arrayable|Jsonable $data 数据
     * @return ResponseInterface 返回ResponseInterface
     */
    protected function error(string $message = 'error', int $code = 1, $data = []): ResponseInterface
    {
        return $this->response->json($this->data($data, $code, $message));
    }

    /**
     * @param array|Arrayable|Jsonable $data 数据
     * @param int $code 消息码
     * @param string $message 消息
     * @return array 返回数组
     */
    protected function data($data, int $code = 0, string $message = 'success'): array
    {
        return compact('code', 'message', 'data');
    }
}
